//
//  PopoverPresentionController.swift
//  SwiftWeibo
//
//  Created by Lucky on 16/5/6.
//  Copyright © 2016年 Lucky. All rights reserved.
//

import UIKit

class PopoverPresentionController: UIPresentationController {
    
    var presentFrame = CGRectZero
    
    /**
     初始化方法，用户创建负责转场动画的对象
     
     - parameter presentedViewController:  被展现的控制器
     - parameter presentingViewController: 发起的控制器
     
     - returns: 负责转场动画的对象
     */
    override init(presentedViewController: UIViewController, presentingViewController: UIViewController) {
        super.init(presentedViewController: presentedViewController, presentingViewController: presentingViewController)
        print(presentedViewController)
    }
    
    /**
     即将布局转场子视图时调用
     */
    override func containerViewWillLayoutSubviews() {
        // containerView 容器视图
        // presentedView() 被展现的视图
        
        if presentFrame == CGRectZero {
            presentedView()?.frame = CGRect(x: UIScreen.mainScreen().bounds.size.width * 0.5 - 100, y: 56, width: 200, height: 200)
        } else {
            presentedView()?.frame = presentFrame
        }
        
        print(presentFrame)
        
        containerView?.insertSubview(corverView, atIndex: 0)
    }
    
    // MARK: - 懒加载
    private lazy var corverView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(white: 0.0, alpha: 0.2)
        view.frame = UIScreen.mainScreen().bounds
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(PopoverPresentionController.close))
        view.addGestureRecognizer(tap)
        
        return view
    }()

    // MARK: - 内部处理
    func close() -> () {
        presentedViewController.dismissViewControllerAnimated(true, completion: nil)
    }
}
